/**
 * @author harae Feng
 * @date 2019-09-11
 * @Last Modified by: harae Feng
 * @Describe api 封装
 */

const route = require('koa-router')()
const index = require('./index')
const fs = require('fs')
const path = require('path')

route.prefix('/api')

route.get('/test/:name', async (ctx, next) => {
    let name = ctx.params.name
    ctx.response.body = `<h1>Hello, this is ${name}'s MusicAPI. </h1>`
})

// 运行
autoReadFileToAPI()

/**
 *自动读取文件名，挂载API
 *
 */
function autoReadFileToAPI(){
    try {
        fs.readdirSync(path.join(__dirname, './_api')).reverse().forEach(dir=>{
            // _autoapi_ 的文件名直接过滤
            if(dir.indexOf('_autoapi_') === -1){
                return;
            }
            // _autoapi_的文件名自动挂载api
            route.use(require(`./_api/${dir}`).routes())
        })
    } catch (error) {
        console.warn(`自动挂载API出错，e：${error}`)
    }
}


module.exports = route